import md5 from './md5.min.js'

function uuid() {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	return uuid;
}

function reverse(str) {
	return str.split('').reverse().join('')
}
//生成时间戳
function createTimestamp() {
	return parseInt(new Date().getTime()) + '';
}
//转qq经纬度
function BMapTransqqMap(lng, lat) {
	let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
	let x = lng;
	let y = lat;
	let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
	let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
	let lngs = z * Math.cos(theta) - 0.0065;
	let lats = z * Math.sin(theta) - 0.006;

	return {
		lng: lngs.toFixed(7),
		lat: lats.toFixed(7)
	}
}

//转百度经纬度
function qqMapTransBMap(lng, lat) {
	let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
	let x = lng;
	let y = lat;
	let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
	let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
	let lngs = z * Math.cos(theta) + 0.0065;
	let lats = z * Math.sin(theta) + 0.006;

	return {
		lng: lngs.toFixed(7),
		lat: lats.toFixed(7)
	}
}
//进行经纬度转换为距离的计算
function Rad(d) {
	return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
}
//计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
function GetDistance(lat1, lng1, lat2, lng2) {
	var radLat1 = Rad(lat1);
	var radLat2 = Rad(lat2);
	var a = radLat1 - radLat2;
	var b = Rad(lng1) - Rad(lng2);
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
		Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
	s = s * 6378.137; // EARTH_RADIUS;
	s = Math.round(s * 10000) / 10000; //输出为公里
	var distance = s;
	var distance_str = "";
	if (parseInt(distance) >= 1) {
		s = distance_str = distance.toFixed(1) + "km";
	} else {
		s = distance_str = parseInt((distance * 1000)) + "m";
	}
	return s;
}
//将毫秒转成时分秒	
function formatSeconds(value) {
	var theTime = parseInt(value); // 秒
	var theTime1 = 0; // 分
	var theTime2 = 0; // 小时
	// alert(theTime);
	if (theTime > 60) {
		theTime1 = parseInt(theTime / 60);
		theTime = parseInt(theTime % 60);
		// alert(theTime1+"-"+theTime);
		if (theTime1 > 60) {
			theTime2 = parseInt(theTime1 / 60);
			theTime1 = parseInt(theTime1 % 60);
		}
	}
	var result = "" + parseInt(theTime) + "秒";
	if (theTime1 > 0) {
		result = "" + parseInt(theTime1) + "分" + result;
	}
	if (theTime2 > 0) {
		result = "" + parseInt(theTime2) + "小时" + result;
	}
	return result;
}

const BASE_URL = 'https://api.youmichemeng.com/api/'
export const myRequest = (options) => {
		// 异步封装，通过Promise返回
		return new Promise((resolve, reject) => {

			uni.showLoading({
				title: '加载中',
				mask: true
			})

			let token;

			// 没有登录的生产环境
			token = uni.getStorageSync('token') || '&^%$#@w2sdf982w983skjdfwe(**$%^&'
			//判断设备 是支付宝 微信  还是h5
			const data = {
				imei: 'mini',

				// #ifdef H5
				imei: 'web'
				// #endif
				cs: uuid(),
				ver: 11,
				plat: 'mini',

				utype: '0',
				...options.data
			}

			if (!data.phone) {
				var p = uni.getStorageSync('phone');
				data.phone = p;
			}

			const ordered = {};
			Object.keys(data).sort().forEach(function(key) {
				ordered[key] = data[key];
			});
			let param_list = []
			for (let k in ordered) {
				param_list.push(String(k) + String(data[k]))
			}
			let param = param_list.join('')
			// var hash = md5.create();
			// hash.update('Message to hash');
			// hash.hex();
			param = token + reverse(param.toLowerCase()) + reverse(token)
			data.sn = md5(param);



			const res = uni.request({
				url: BASE_URL + options.url,
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				data,


				// 请求数据成功
				success: (res) => {

					if (res.statusCode === 200) {

						if (res.data.status == 0) {
							// resolve(res.data)
							
						resolve({
							return: res.data
						})
							// resolve({
							// 	return: res.data
							// })
                           
						} else if(res.result.status === 1)  {
							console.log('请先进行登录。');
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/login/login'
								})
							}, 1000)
					
						}else{
							
							// reject(res.data)
							reject({
								return: res.data
							})
						}
                          uni.hideLoading()
					} else {
                        uni.hideLoading()
						reject(new Error(`${res.statusCode} ${res.data}`))
					}

				},


				fail: (err) => {

					console.log(err)
					reject(e)
				},
				complete: () => {
					uni.hideLoading()
				}


			})



		})
		
		}

	//封装消息提示框
	const toast = function(title, icon = 'none', duration, options) {
		setTimeout(() => {
			wx.showToast({
				title: title || '',
				icon: icon,
			});
			setTimeout(() => {
				wx.hideToast();
			}, 2000)
		}, 300);
	
	}
